package com.kanshu.ksgb.fastread.doudou.module.personal.activity

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.kanshu.ksgb.fastread.doudou.R
import com.kanshu.ksgb.fastread.doudou.app.constants.ARouterConfig
import com.kanshu.ksgb.fastread.doudou.base.baseui.BaseActivity
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseResult
import com.kanshu.ksgb.fastread.doudou.common.net.retrofit.RetrofitHelper
import com.kanshu.ksgb.fastread.doudou.common.net.retrofit.SimpleRetrofit
import com.kanshu.ksgb.fastread.doudou.common.util.ToastUtil
import com.kanshu.ksgb.fastread.doudou.module.login.bean.AliAuthParams
import com.kanshu.ksgb.fastread.doudou.module.login.thirdlogin.AlipayLogin
import com.kanshu.ksgb.fastread.doudou.module.login.thirdlogin.WxLogin
import com.kanshu.ksgb.fastread.doudou.module.personal.bean.BindInfo
import com.kanshu.ksgb.fastread.doudou.module.personal.bean.UpdateInfoEvent
import com.kanshu.ksgb.fastread.doudou.module.personal.presenter.PersonCenterService
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_bind_account.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

@Route(path = ARouterConfig.PERSONAL_BIND_ACCOUNT)
class BindAccountActivity : BaseActivity() {

    private var infoLoaded = false
    private var alipayInfo:BindInfo? = null
    private var wechatInfo:BindInfo? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_bind_account)
        title = "绑定提现账号"
        btn_alipay.setOnClickListener {
            if(!infoLoaded){
                ToastUtil.showMessage("信息加载中，请稍后再试")
                return@setOnClickListener
            }
            if(alipayInfo == null){
                bindAlipay()
            }else{
                ToastUtil.showMessage("你已绑定")
            }

        }
        btn_wechat.setOnClickListener {
            if(!infoLoaded){
                ToastUtil.showMessage("信息加载中，请稍后再试")
                return@setOnClickListener
            }
            if(wechatInfo == null) {
                bindWechat()
            }else{
                ToastUtil.showMessage("你已绑定")
            }
        }
        loadBindInfo()
        EventBus.getDefault().register(this)
    }

    private fun bindWechat() {
        WxLogin.bindWithdraw(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    fun checkAliPayInstalled(context: Context): Boolean {

        val uri = Uri.parse("alipays://platformapi/startApp")
        val intent = Intent(Intent.ACTION_VIEW, uri)
        val componentName = intent.resolveActivity(context.getPackageManager())
        return componentName != null
    }

    private fun bindAlipay() {
//        var exist = false
//        try{
//            val alipayApp = packageManager.getPackageInfo("com.eg.android.AlipayGphone",PackageManager.GET_META_DATA)
//            exist = true
//        }catch ( e:Exception){
//            e?.printStackTrace()
//        }
        val exist = checkAliPayInstalled(this)
        if(!exist){
            ToastUtil.showMessage("请安装支付宝")
            return
        }


        val retrofitHelper = RetrofitHelper.getInstance()
        retrofitHelper.createService(PersonCenterService::class.java)
                .getAliAuthParams()
                .compose(asyncRequest())
                .subscribe(object: Observer<BaseResult<AliAuthParams>>{
                    override fun onComplete() {
                        dismissLoading()
                    }

                    override fun onSubscribe(d: Disposable?) {
                        showLoading("")
                    }

                    override fun onNext(t: BaseResult<AliAuthParams>?) {
                        val result = t?.result?.data
                        if(result != null){
                            val helper = AlipayLogin(this@BindAccountActivity)
                            helper.bindAliPayUser(result.sign,result.target_id)
                        }else{
                            Log.i("test", "${t?.result?.status?.msg}")
                        }
                    }

                    override fun onError(e: Throwable?) {
                        e?.printStackTrace()
                        dismissLoading()
                    }
                })
    }


    private fun updateAlipayView(name:String?){
        if(!TextUtils.isEmpty(name)){
            alipay_ic_binded.visibility  = View.VISIBLE
            txt_alipay.text= "已绑定$name"
        }else{
            alipay_ic_binded.visibility  = View.INVISIBLE
            txt_alipay.text= getString(R.string.unbind_alipay)
        }
    }


    private fun updateWechatView(name:String?){
        if(!TextUtils.isEmpty(name)){
            wechat_ic_binded.visibility  = View.VISIBLE
            txt_wechat.text= "已绑定$name"
        }else{
            wechat_ic_binded.visibility  = View.INVISIBLE
            txt_wechat.text= getString(R.string.unbind_wechat)
        }
    }

    private fun loadBindInfo(){
        val retrofitHelper = RetrofitHelper.getInstance()
        retrofitHelper.createService(PersonCenterService::class.java)
                .getAccountBindInfo()
                .compose(asyncRequest())
                .subscribe(object: Observer<BaseResult<List<BindInfo>>>{
                    override fun onComplete() {
                        dismissLoading()
                    }

                    override fun onSubscribe(d: Disposable?) {
                        showLoading("")
                    }

                    override fun onNext(t: BaseResult<List<BindInfo>>?) {
                        infoLoaded = true
                        val size = t?.result?.data?.size?:0
                        if(size != 0 ){
                            t?.result?.data?.forEach {
                                when(it.type){
                                    BindInfo.TYPE_ALIPAY-> {
                                        alipayInfo = it
                                        updateAlipayView(it.nickname)
                                    }
                                    BindInfo.TYPE_WECHAT-> {
                                        wechatInfo = it
                                        updateWechatView(it.nickname)
                                    }
                                    else -> Log.i("test", "code error ${it.type}")
                                }

                            }

                        }else{
                            updateAlipayView(null)
                            updateWechatView(null)
                        }

                    }

                    override fun onError(e: Throwable?) {
                        infoLoaded = true
                        dismissLoading()
                        e?.printStackTrace()
                    }
                })
    }


    @Subscribe(threadMode = ThreadMode.MAIN, priority = 100)
    fun handleBindEvent(event: BindInfo) {
        if(!event.result){
            ToastUtil.showMessage("绑定失败")
            return
        }
        when(event.type){
            BindInfo.TYPE_ALIPAY-> {
                uploadAlipayInfo(event)
            }
            BindInfo.TYPE_WECHAT-> updateWechatView(event.nickname)
            else -> Log.i("test", "code error ${event.type}")
        }
    }

    private fun uploadAlipayInfo(info: BindInfo) {
        val apiService = SimpleRetrofit.getInstance().create(PersonCenterService::class.java)
        apiService.postAlipayAuthCode(info.authorization_id)
                .compose(asyncRequest())
                .subscribe(object :Observer<BaseResult<String>>{
                    override fun onComplete() {
                        dismissLoading()
                    }

                    override fun onSubscribe(d: Disposable?) {
                        showLoading("")
                    }

                    override fun onNext(t:BaseResult<String>?) {
                        val code =  t?.result?.status?.code?: -1
                        var msg = "绑定成功"
                        if(code != 0){
                           msg = "绑定失败${t?.result?.status?.msg}"
                        }else{
                            EventBus.getDefault().post(UpdateInfoEvent())
                            loadBindInfo()
                        }
                        ToastUtil.showMessage(msg)
                    }

                    override fun onError(e: Throwable?) {
                        dismissLoading()
                        e?.printStackTrace()
                    }
                })

    }

    companion object {
        fun actionStart(activity: Activity){
            val intent = Intent(activity,BindAccountActivity::class.java)
            activity.startActivity(intent)
        }
    }


}
